package command;

import java.util.Stack;

/**
 * 遥控器实现命令模式，用于操作农业设备
 */
public class RemoteController {
    private Command command;
    private final Stack<Command> commandHistory = new Stack<>();
    private final AgriculturalDevice device;

    public RemoteController(AgriculturalDevice device) {
        this.device = device;
        this.command = new NoCommand(); // 初始化空命令
    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {
        if (command == null) {
            System.out.println("错误：未设置有效命令");
            return;
        }
        command.execute();
        commandHistory.push(command);
    }

public void pressUndo() {
    if (!commandHistory.isEmpty()) {
        Command lastCommand = commandHistory.pop();
        lastCommand.undo();

        // 如果是调整命令，我们需要特殊处理参数历史
        if (lastCommand instanceof AdjustCommand) {
            // 查找历史中前一个调整命令
            AdjustCommand prevAdjustCommand = findPreviousAdjustCommand();
            if (prevAdjustCommand != null) {
                // 更新设备参数为前一个调整命令的参数
                device.adjust(prevAdjustCommand.getNewParams());
            } else {
                // 如果没有前一个调整命令，恢复到最初参数
                device.adjust(((AdjustCommand) lastCommand).getOldParams());
            }
        }
    } else {
        System.out.println("没有可撤销的命令");
    }
}

    // 辅助方法：查找前一个调整命令
    private AdjustCommand findPreviousAdjustCommand() {
        for (int i = commandHistory.size() - 1; i >= 0; i--) {
            Command cmd = commandHistory.get(i);
            if (cmd instanceof AdjustCommand) {
                return (AdjustCommand) cmd;
            }
        }
        return null;
    }
    // 便捷方法
    public void startDevice() {
        setCommand(new StartCommand(device));
        pressButton();
    }

    public void stopDevice() {
        setCommand(new StopCommand(device));
        pressButton();
    }

    public void adjustDevice(String params) {
        setCommand(new AdjustCommand(device, params));
        pressButton();
    }

    public void emergencyStop() {
        setCommand(new EmergencyStopCommand(device));
        pressButton();
    }

    // 获取命令历史（用于调试）
    public Stack<Command> getCommandHistory() {
        return commandHistory;
    }
}
